package resputil

import (
	"gitee.com/Rankx_code/ego-component/utils/errorx"
	"google.golang.org/grpc/status"
)

const (
	ErrCodeSuccess = 0 //
)

// ParseError 解析error，返回错误码和错写信息
func ParseError(err error) (errCode int32, msg string) {
	if err == nil {
		return
	}

	switch e := err.(type) {
	case errorx.Error: // 经过wrap过的
		serviceErr, ok := errorx.IsServiceErr(e, e.Errors...)
		if ok {
			errCode = int32(serviceErr.Errcode)
			msg = serviceErr.Errmsg
			return
		}

		if e.E != nil {
			// grpc 错误
			gErr := status.Convert(e.E)
			errCode = int32(gErr.Code())
			msg = gErr.Message()
			return
		}
	case errorx.ServiceError:
		errCode = int32(e.Errcode)
		msg = e.Errmsg
		return
	default:
		// 走默认实现
	}

	// grpc错误转换
	gErr := status.Convert(err)
	errCode = int32(gErr.Code())
	msg = gErr.Message()
	if errCode == 0 {
		errCode = 99 // 默认给99的错误码
	}
	return
}

// OnFailed 失败
func OnFailed(err error) CommResp {
	errCode, msg := ParseError(err)
	r := CommResp{
		ErrNo:      errCode,
		ErrMsg:     msg,
		StackTrace: err,
	}
	return r
}

// OnSuccess 成功响应
func OnSuccess(data interface{}) CommResp {
	r := CommResp{
		ErrNo:  ErrCodeSuccess,
		ErrMsg: "",
		Data:   data,
	}
	return r
}
